package lc.q350_400;

import java.util.*;

public class Q368 {

    public static void main(String[] args) {
        Q368 q368 = new Q368();
        System.out.println(q368.largestDivisibleSubset2(new int[]{5,9,18,54,108,540,90,180,360,720}));
    }

    public List<Integer> largestDivisibleSubset2(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        int maxSize = 1;
        int maxVal = nums[0];
        for (int i = 1; i < n; i++) {
            int num = nums[i];
            for (int j = 0; j < i; j++) {
                if (num % nums[j] == 0) {
                    dp[i] = Integer.max(dp[j] + 1, dp[i]);
                }
            }
            if (dp[i] > maxSize) {
                maxSize = dp[i];
                maxVal = num;
            }
        }
        List<Integer> res = new ArrayList<>();
        for (int i = n - 1; i >= 0 && maxSize > 0; i--) {
            if (dp[i] == maxSize && maxVal % nums[i] == 0) {
                res.add(nums[i]);
                maxVal = nums[i];
                maxSize --;
            }
        }
        return res;
    }

    public List<Integer> largestDivisibleSubset(int[] nums) {
        Arrays.sort(nums);
        // dp[i]是包含nums[i]的最大的
        List<List<Integer>> dp = new ArrayList<>();
        dp.add(Collections.singletonList(nums[0]));
        int maxIndex = 0;
        for (int i = 1; i < nums.length; i++) {
            int num = nums[i];
            List<Integer> maxList = new ArrayList<>();
            for (int i1 = i - 1; i1 >= 0; i1--) {
                int num1 = nums[i1];
                if (dp.get(i1).size()  > maxList.size() && num % num1 == 0) {
                    maxList = dp.get(i1);
                }
            }
            ArrayList<Integer> next = new ArrayList<>(maxList);
            next.add(num);
            dp.add(next);
            if (next.size() > dp.get(maxIndex).size()) {
                maxIndex = i;
            }
        }
        return dp.get(maxIndex);
    }
}
